import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import Forbidden from '@/views/Forbidden.vue'
import NotFound from '@/views/404.vue'
import Maintenance from '@/views/Maintenance.vue'
import axios from 'axios'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/maintenance', component: Maintenance },
  { 
    path: '/user',
    component: () => import('@/views/user/Home.vue'),
    redirect: '/user/dashboard',
    children: [
      { path: 'dashboard', component: () => import('@/views/user/Dashboard.vue') },
      { path: 'rescue', component: () => import('@/views/user/RescueManage.vue') },
      { path: 'animals', component: () => import('@/views/user/AnimalList.vue') },
      { path: 'adoption', component: () => import('@/views/user/Adoption.vue') },
      { path: 'profile', component: () => import('@/views/user/Profile.vue') },
      { path: 'message', component: () => import('@/views/user/MessageBoard.vue') },
      { path: 'volunteerApply', component: () => import('@/views/user/VolunteerApply.vue') },
      { path: 'animal/:id', component: () => import('@/views/user/AnimalDetail.vue') },
      { path: 'adoptForm/:id', component: () => import('@/views/user/AdoptForm.vue') },
      { path: 'news/:id', component: () => import('@/views/user/NewsDetail.vue') }
      
    ]
  },
  { 
    path: '/volunteer',
    component: () => import('@/views/volunteer/Home.vue'),
    redirect: '/volunteer/dashboard',
    children: [
      { path: 'dashboard', component: () => import('@/views/volunteer/Dashboard.vue') },
      { path: 'adoptionReview', component: () => import('@/views/admin/AdoptionReview.vue') },
      { path: 'rescueInfo', component: () => import('@/views/admin/RescueInfo.vue') },
      { path: 'rescueRecordManage', component: () => import('@/views/admin/RescueRecordManage.vue') },
      { path: 'animalManage', component: () => import('@/views/admin/AnimalManage.vue') },
      { path: 'healthRecordManage', component: () => import('@/views/admin/HealthRecordManage.vue') },
      { path: 'rescueStoryManage', component: () => import('@/views/admin/RescueStoryManage.vue') },
      { path: 'profile', component: () => import('@/views/user/Profile.vue') },
      { path: 'news/:id', component: () => import('@/views/volunteer/NewsDetail.vue') }
    ]
  },
  { 
    path: '/admin',
    component: () => import('@/views/admin/Home.vue'),
    redirect: '/admin/home',
    children: [
      { path: 'home', component: () => import('@/views/admin/Dashboard.vue') },
      { path: 'adoptionReview', component: () => import('@/views/admin/AdoptionReview.vue') },
      { path: 'announcement', component: () => import('@/views/admin/Announcement.vue') },
      { path: 'news', component: () => import('@/views/admin/News.vue') },
      { path: 'animalManage', component: () => import('@/views/admin/AnimalManage.vue') },
      { path: 'healthRecordManage', component: () => import('@/views/admin/HealthRecordManage.vue') },
      { path: 'rescueStoryManage', component: () => import('@/views/admin/RescueStoryManage.vue') },
      { path: 'rescueInfo', component: () => import('@/views/admin/RescueInfo.vue') },
      { path: 'rescueRecordManage', component: () => import('@/views/admin/RescueRecordManage.vue') },
      { path: 'userManage', component: () => import('@/views/admin/UserManage.vue') },
      { path: 'volunteerReview', component: () => import('@/views/admin/VolunteerReview.vue') },
      { path: 'profile', component: () => import('@/views/admin/Profile.vue') },
      { path: 'messageManage', component: () => import('@/views/admin/AdminMessage.vue') },
      { path: 'systemSettings', component: () => import('@/views/admin/SystemSettings.vue') },
      { path: 'systemLog', component: () => import('@/views/admin/SystemLog.vue') },
      { path: 'userLoginInfo', component: () => import('@/views/admin/UserLoginInfo.vue') },
    ]
  },
  { path: '/components/AnnouncementDialog', component: () => import('@/views/components/AnnouncementDialog.vue') },
  { path: '/403', component: Forbidden },
  { path: '/404', component: NotFound },
  { path: '/:catchAll(.*)', component: NotFound }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // maintenance/403/404 总是允许
  if (to.path === '/maintenance' || to.path === '/403' || to.path === '/404') {
    next()
    return
  }

  // 检查维护模式（只对普通用户和志愿者生效）
  if (to.path !== '/login' && to.path !== '/register') {
    try {
      const res = await axios.get('http://localhost:8080/api/admin/system-setting/key/maintenance_mode')
      if (res.data.code === 200 && res.data.data) {
        const maintenanceMode = res.data.data.settingValue === '1' || res.data.data.status === 1
        if (maintenanceMode) {
          const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
          const roleId = Number(localStorage.getItem('roleId'))
          // 管理员不受维护模式影响
          if (isLoggedIn && roleId === 3) {
            // 管理员可以正常访问
          } else {
            // 普通用户和志愿者跳转到维护页面
            next('/maintenance')
            return
          }
        }
      }
    } catch (error) {
      console.error('检查维护模式失败:', error)
      // 检查失败不影响正常访问
    }
  }

  // login/register 总是允许
  if (to.path === '/login' || to.path === '/register') {
    next()
    return
  }

  // 判断是否登录
  const isLoggedIn = localStorage.getItem('isLoggedIn') === 'true'
  const roleId = Number(localStorage.getItem('roleId'))

  if (!isLoggedIn) {
    next('/403') // 未登录禁止访问
    return
  }

  // 根据 roleId 限制页面访问
  if (to.path.startsWith('/user') && roleId !== 1) next('/403')
  else if (to.path.startsWith('/volunteer') && roleId !== 2) next('/403')
  else if (to.path.startsWith('/admin') && roleId !== 3) next('/403')
  else next() // 正常访问
})

export default router







// import { createRouter, createWebHistory } from 'vue-router'
// import Login from '@/views/Login.vue'
// import Register from '@/views/Register.vue'
// import UserHome from '@/views/user/Home.vue'
// import VolunteerHome from '@/views/volunteer/Home.vue'
// import AdminHome from '@/views/admin/Home.vue'
// import Forbidden from '@/views/Forbidden.vue'

// const routes = [
//   { path: '/', redirect: '/login' },
//   { path: '/login', component: Login },
//   { path: '/register', component: Register },
//   { path: '/user/home', component: UserHome },
//   { path: '/volunteer/home', component: VolunteerHome },
//   { path: '/admin/home', component: AdminHome },
//   { path: '/405', component: Forbidden },
//   { path: '/:catchAll(.*)', redirect: '/405' },
// ]

// const router = createRouter({
//   history: createWebHistory(),
//   routes,
// })

// router.beforeEach((to, from, next) => {
//   // login/register/405 可以随时访问
//   if (to.path === '/login' || to.path === '/register' || to.path === '/405') {
//     next()
//     return
//   }

//   // 如果是前端跳转（from.path 不为空并且不是 405）
//   if (from.path && from.path !== '/405') {
//     next()
//   } else {
//     // 用户手动输入地址 → 跳 405
//     next('/405')
//   }
// })

// export default router
